import { defineStore } from "pinia";

// 支出分类常量
export const EXPENSE_CATEGORIES = [
  { id: "all", name: "全部", icon: "all" },
  { id: "food", name: "餐饮", icon: "food" },
  { id: "shopping", name: "购物", icon: "shopping" },
  { id: "transport", name: "交通", icon: "transport" },
  { id: "entertainment", name: "娱乐", icon: "entertainment" },
  { id: "housing", name: "住房", icon: "housing" },
  { id: "education", name: "教育", icon: "education" },
  { id: "health", name: "医疗", icon: "health" },
  { id: "travel", name: "旅行", icon: "picture" },
  { id: "other", name: "其他", icon: "more" },
];

// 创建支出store
export const useExpenseStore = defineStore("expense", {
  // 状态
  state: () => ({
    expenses: [],
    searchKeyword: "",
    selectedCategory: "all",
    selectedDateRange: {
      start: null,
      end: null,
    },
  }),

  // 计算属性
  getters: {
    // 根据搜索关键词、选中分类和日期范围过滤支出
    filteredExpenses: (state) => {
      let result = state.expenses;

      // 搜索过滤
      if (state.searchKeyword) {
        const keyword = state.searchKeyword.toLowerCase();
        result = result.filter((expense) => {
          return expense.description.toLowerCase().includes(keyword) || expense.category.toLowerCase().includes(keyword);
        });
      }

      // 分类过滤
      if (state.selectedCategory !== "all") {
        result = result.filter((expense) => expense.category === state.selectedCategory);
      }

      // 日期范围过滤
      if (state.selectedDateRange.start && state.selectedDateRange.end) {
        const startDate = new Date(state.selectedDateRange.start);
        const endDate = new Date(state.selectedDateRange.end);
        endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间

        result = result.filter((expense) => {
          const expenseDate = new Date(expense.date);
          return expenseDate >= startDate && expenseDate <= endDate;
        });
      }

      // 按日期排序，最新的在前面
      return result.sort((a, b) => new Date(b.date) - new Date(a.date));
    },

    // 获取各分类的支出金额统计
    categoryStats: (state) => {
      const stats = {};

      // 初始化所有分类的金额为0
      EXPENSE_CATEGORIES.forEach((category) => {
        stats[category.id] = 0;
      });

      // 计算各分类的支出金额
      state.expenses.forEach((expense) => {
        stats[expense.category] += expense.amount;
        stats["all"] += expense.amount;
      });

      return stats;
    },

    // 获取日期统计数据
    dateStats: (state) => {
      const stats = {};

      // 按日期分组统计
      state.expenses.forEach((expense) => {
        const dateKey = expense.date.split("T")[0]; // 提取日期部分
        if (!stats[dateKey]) {
          stats[dateKey] = 0;
        }
        stats[dateKey] += expense.amount;
      });

      return stats;
    },

    // 获取月度统计数据
    monthStats: (state) => {
      const stats = {};

      // 按月份分组统计
      state.expenses.forEach((expense) => {
        const date = new Date(expense.date);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;

        if (!stats[monthKey]) {
          stats[monthKey] = 0;
        }
        stats[monthKey] += expense.amount;
      });

      return stats;
    },

    // 获取总支出
    totalExpense: (state) => {
      return state.expenses.reduce((total, expense) => total + expense.amount, 0);
    },
  },

  // 操作方法
  actions: {
    // 添加支出
    addExpense(expenseData) {
      const now = new Date().toISOString();
      const newExpense = {
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        ...expenseData,
        date: expenseData.date || now,
        createdAt: now,
      };

      this.expenses.push(newExpense);
      return newExpense;
    },

    // 更新支出
    updateExpense(id, expenseData) {
      const index = this.expenses.findIndex((expense) => expense.id === id);
      if (index !== -1) {
        // 更新支出信息
        this.expenses[index] = {
          ...this.expenses[index],
          ...expenseData,
          updatedAt: new Date().toISOString(),
        };

        return this.expenses[index];
      }
      return null;
    },

    // 删除支出
    deleteExpense(id) {
      const index = this.expenses.findIndex((expense) => expense.id === id);
      if (index !== -1) {
        this.expenses.splice(index, 1);
        return true;
      }
      return false;
    },

    // 设置搜索关键词
    setSearchKeyword(keyword) {
      this.searchKeyword = keyword;
    },

    // 设置选中的分类
    setSelectedCategory(categoryId) {
      this.selectedCategory = categoryId;
    },

    // 设置日期范围
    setDateRange(start, end) {
      this.selectedDateRange = { start, end };
    },

    // 清空搜索和筛选
    clearFilters() {
      this.searchKeyword = "";
      this.selectedCategory = "all";
      this.selectedDateRange = { start: null, end: null };
    },

    // 添加示例数据（用于测试）
    addSampleData() {
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      const twoDaysAgo = new Date(today);
      twoDaysAgo.setDate(twoDaysAgo.getDate() - 2);
      const lastWeek = new Date(today);
      lastWeek.setDate(lastWeek.getDate() - 7);

      const sampleExpenses = [
        {
          description: "午餐",
          amount: 35.5,
          category: "food",
          date: today.toISOString(),
        },
        {
          description: "打车",
          amount: 25,
          category: "transport",
          date: today.toISOString(),
        },
        {
          description: "电影票",
          amount: 80,
          category: "entertainment",
          date: yesterday.toISOString(),
        },
        {
          description: "超市购物",
          amount: 156.8,
          category: "shopping",
          date: twoDaysAgo.toISOString(),
        },
        {
          description: "房租",
          amount: 2500,
          category: "housing",
          date: lastWeek.toISOString(),
        },
      ];

      sampleExpenses.forEach((expense) => {
        this.addExpense(expense);
      });
    },
  },

  // 持久化配置
  persist: {
    key: "expense-store",
    paths: ["expenses"],
    storage: {
      getItem(key) {
        return uni.getStorageSync(key);
      },
      setItem(key, value) {
        uni.setStorageSync(key, value);
      },
      removeItem(key) {
        uni.removeStorageSync(key);
      },
    },
  },
});
